{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting ./mnist/train-images-idx3-ubyte.gz\n",
      "Extracting ./mnist/train-labels-idx1-ubyte.gz\n",
      "Extracting ./mnist/t10k-images-idx3-ubyte.gz\n",
      "Extracting ./mnist/t10k-labels-idx1-ubyte.gz\n",
      "('Epoch:', '0001', 'cost=', '215.548141965')\n",
      "('Epoch:', '0002', 'cost=', '54.977557694')\n",
      "('Epoch:', '0003', 'cost=', '33.899888993')\n",
      "('Epoch:', '0004', 'cost=', '23.234023376')\n",
      "('Epoch:', '0005', 'cost=', '16.552313167')\n",
      "('Epoch:', '0006', 'cost=', '12.184614655')\n",
      "('Epoch:', '0007', 'cost=', '8.918999288')\n",
      "('Epoch:', '0008', 'cost=', '6.555203167')\n",
      "('Epoch:', '0009', 'cost=', '4.864825427')\n",
      "('Epoch:', '0010', 'cost=', '3.541727996')\n",
      "('Epoch:', '0011', 'cost=', '2.601980731')\n",
      "('Epoch:', '0012', 'cost=', '2.013708151')\n",
      "('Epoch:', '0013', 'cost=', '1.447752024')\n",
      "('Epoch:', '0014', 'cost=', '1.284220558')\n",
      "('Epoch:', '0015', 'cost=', '1.063494972')\n",
      "('Epoch:', '0016', 'cost=', '1.089214503')\n",
      "('Epoch:', '0017', 'cost=', '0.819465103')\n",
      "('Epoch:', '0018', 'cost=', '0.826465986')\n",
      "('Epoch:', '0019', 'cost=', '0.756363073')\n",
      "('Epoch:', '0020', 'cost=', '0.756904836')\n",
      "('Epoch:', '0021', 'cost=', '0.772401051')\n",
      "('Epoch:', '0022', 'cost=', '0.591537078')\n",
      "('Epoch:', '0023', 'cost=', '0.518754110')\n",
      "('Epoch:', '0024', 'cost=', '0.653424654')\n",
      "('Epoch:', '0025', 'cost=', '0.639180361')\n",
      "('Epoch:', '0026', 'cost=', '0.418257485')\n",
      "('Epoch:', '0027', 'cost=', '0.434976982')\n",
      "('Epoch:', '0028', 'cost=', '0.606400410')\n",
      "('Epoch:', '0029', 'cost=', '0.475488307')\n",
      "('Epoch:', '0030', 'cost=', '0.458589170')\n",
      "Optimization Finished!\n",
      "('Accuracy:', 0.96039999)\n"
     ]
    }
   ],
   "source": [
    "#get the mnist data \n",
    "# wget http://deeplearning.net/data/mnist/mnist.pkl.gz\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "mnist = input_data.read_data_sets(\"./mnist/\", one_hot=True)\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "# Parameters\n",
    "learning_rate = 0.001\n",
    "training_epochs = 30\n",
    "batch_size = 100\n",
    "display_step = 1\n",
    "\n",
    "# Network Parameters\n",
    "n_hidden_1 = 256 # 1st layer number of features\n",
    "n_hidden_2 = 512 # 2nd layer number of features\n",
    "n_input = 784 # MNIST data input (img shape: 28*28)\n",
    "n_classes = 10 # MNIST total classes (0-9 digits)\n",
    "\n",
    "# tf Graph input\n",
    "x = tf.placeholder(\"float\", [None, n_input])\n",
    "y = tf.placeholder(\"float\", [None, n_classes])\n",
    "\n",
    "\n",
    "# Create model\n",
    "def multilayer_perceptron(x, weights, biases):\n",
    "    # Hidden layer with RELU activation\n",
    "    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])\n",
    "    layer_1 = tf.nn.relu(layer_1)\n",
    "    # Hidden layer with RELU activation\n",
    "    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])\n",
    "    layer_2 = tf.nn.relu(layer_2)\n",
    "\n",
    "    # layer_3 = tf.add(tf.matmul(layer_2, weights['h3']), biases['b3'])\n",
    "    # layer_3 = tf.nn.relu(layer_3)\n",
    "\n",
    "\n",
    "\n",
    "    #we can add dropout layer\n",
    "    # drop_out = tf.nn.dropout(layer_2, 0.75)\n",
    "\n",
    "\n",
    "\n",
    "    # Output layer with linear activation\n",
    "    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']\n",
    "    return out_layer\n",
    "\n",
    "# Store layers weight & biases\n",
    "weights = {\n",
    "    #you can change \n",
    "    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),\n",
    "    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n",
    "    #'h3': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),\n",
    "    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))\n",
    "}\n",
    "biases = {\n",
    "    'b1': tf.Variable(tf.random_normal([n_hidden_1])),\n",
    "    'b2': tf.Variable(tf.random_normal([n_hidden_2])),\n",
    "    #'b3': tf.Variable(tf.random_normal([n_hidden_2])),\n",
    "    'out': tf.Variable(tf.random_normal([n_classes]))\n",
    "}\n",
    "\n",
    "# Construct model\n",
    "pred = multilayer_perceptron(x, weights, biases)\n",
    "\n",
    "# Define loss and optimizer\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\n",
    "optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n",
    "\n",
    "# Initializing the variables\n",
    "init = tf.global_variables_initializer()\n",
    "\n",
    "# Launch the graph\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "\n",
    "    # Training cycle\n",
    "    for epoch in range(training_epochs):\n",
    "        avg_cost = 0.\n",
    "        total_batch = int(mnist.train.num_examples/batch_size)\n",
    "        # Loop over all batches\n",
    "        for i in range(total_batch):\n",
    "            batch_x, batch_y = mnist.train.next_batch(batch_size)\n",
    "            # Run optimization op (backprop) and cost op (to get loss value)\n",
    "            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,\n",
    "                                                          y: batch_y})\n",
    "            # Compute average loss\n",
    "            avg_cost += c / total_batch\n",
    "        # Display logs per epoch step\n",
    "        if epoch % display_step == 0:\n",
    "            print(\"Epoch:\", '%04d' % (epoch+1), \"cost=\", \\\n",
    "                \"{:.9f}\".format(avg_cost))\n",
    "    print(\"Optimization Finished!\")\n",
    "\n",
    "    # Test model\n",
    "    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n",
    "    # Calculate accuracy\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n",
    "    print(\"Accuracy:\", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
